package com.bmps.springcloud.insuredmicroservice.service.underwrite.strategy.accumulated;

import com.bmps.springcloud.common.utils.DateUtil;
import com.bmps.springcloud.insuredmicroservice.config.accept.ProductConfig;
import com.bmps.springcloud.insuredmicroservice.constant.accept.AcceptConstant;
import com.bmps.springcloud.insuredmicroservice.constant.accept.QuotaConstant;
import com.bmps.springcloud.insuredmicroservice.constant.accept.UnderWriteConstant;
import com.bmps.springcloud.insuredmicroservice.model.accept.medium.PolicyRiskInfoModel;
import com.bmps.springcloud.insuredmicroservice.model.accept.resquest.*;
import com.bmps.springcloud.insuredmicroservice.model.underwrite.InsuredModel;
import com.bmps.springcloud.insuredmicroservice.repository.underwrite.coresystem.InsuredCoreRepository;
import com.bmps.springcloud.insuredmicroservice.service.RedisService;
import com.bmps.springcloud.insuredmicroservice.service.underwrite.strategy.riskamount.CalculateRiskAmount;
import com.bmps.springcloud.insuredmicroservice.util.accept.AcceptUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * HCT026累计重疾险风险保额
 *
 * @author Jacob
 * @date 2020-04-06 17:39:18
 */
public class Hct026AccumulatedStrategy implements AccumulatedStrategy {
    private Logger logger = LoggerFactory.getLogger(Hct026AccumulatedStrategy.class);

    @Override
    public InsuredModel checkAccumulatedRolesByRiskCode(AcceptRequestDataModel acceptRequestDataModel, InsuredCoreRepository insuredCoreRepository,
                                                        ProductModel productModel, RedisService redisService, ProductConfig productConfig) {
        RequestModel requestModel = acceptRequestDataModel.getRequest();
        PolicyInfoModel policyInfoModel = requestModel.getPolicyInfo();
        String prtNo = policyInfoModel.getPrtNo();
        Date valiDate = requestModel.getPolicyInfo().getCvalidate();
        InsurantModel insurantModel = AcceptUtil.getInsurantModelBySeq(productModel.getProdInsSeq(), requestModel.getCustInfo().getInsurants().getInsurant());
        //计算HCT026险种的历史、当前和缓存保额
        BigDecimal hct026Cache = redisService.getCacheQuota(QuotaConstant.SORT_HCT026, insurantModel.getIdNo(), productModel.getAmnt(), requestModel.getPolicyInfo().getContNo());
        BigDecimal hct026History = BigDecimal.valueOf(insuredCoreRepository.getHCT026InsuranceCount(insurantModel.getInsuredNo(), prtNo));
        BigDecimal hct026Total = productModel.getAmnt().add(hct026Cache).add(hct026History);
        Set riskCodeSet = null;
        try {
            riskCodeSet = redisService.members(AcceptConstant.SERIOUS_ILLNESS_INSURANCE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isEmpty(riskCodeSet)) {
            return AcceptUtil.getInsuredResponse(UnderWriteConstant.UNDER_WRITE_FIAL_CODE,
                    String.format(UnderWriteConstant.EXCEPTION_SERIOUS_ILLNESS, insurantModel.getName()));
        }
        StringBuilder sb = new StringBuilder(16);
        List<ProductModel> productModelList = requestModel.getProductInfo().getProducts().getProduct();
        List<PolicyRiskInfoModel> policyRiskInfoList = new ArrayList<>(productModelList.size());
        for (ProductModel product : productModelList) {
            if (insurantModel.getInsSeq() != product.getProdInsSeq()) {
                continue;
            }
            sb.setLength(0);
            sb.append(AcceptConstant.REDIS_PREFIX_R004).append("|").append(product.getProdCode());
            Object obj = redisService.get(sb.toString());
            if (obj != null) {
                String[] a = String.valueOf(obj).split("\\|");
                if (!(StringUtils.equals(a[4], "1") || StringUtils.equals(a[4], "2"))) {
                    policyRiskInfoList.add(CalculateRiskAmount.getPolicyRiskInfoModel(product, requestModel));
                }
            }
        }
        List<PolicyRiskInfoModel> filterMultiplePayList = policyRiskInfoList.stream().filter(x -> !productConfig.getMultiplePayList().contains(x.getRiskCode())).collect(Collectors.toList());
        //被保人单次给付重疾险保额
        BigDecimal singleNow = CalculateRiskAmount.getSumInsuranceRiskAmount(riskCodeSet, filterMultiplePayList, true);
        BigDecimal singleCache = redisService.getCacheQuota(QuotaConstant.SORT_A_SINGLE, insurantModel.getIdNo(), singleNow, requestModel.getPolicyInfo().getContNo());
        double singleHistory = insuredCoreRepository.getHistorySinglePay(insurantModel.getInsuredNo(), insurantModel.getInsuredNo());
        //全渠道累积重疾险保额
        BigDecimal illnessNow = CalculateRiskAmount.getSumInsuranceRiskAmount(riskCodeSet, policyRiskInfoList, true);
        double illnessHistory = insuredCoreRepository.getSeriousDiseaseInsuranceCount(insurantModel.getInsuredNo(), insurantModel.getInsuredNo());
        //HCT026风险保额
        double riskAmountHistory = insuredCoreRepository.getRiskAmountHct026(insurantModel.getInsuredNo(), insurantModel.getInsuredNo());
        BigDecimal riskAmountCache = redisService.getCacheQuota(QuotaConstant.SORT_RISK_HCT026, insurantModel.getIdNo(), BigDecimal.valueOf(0), requestModel.getPolicyInfo().getContNo());
        // 计算D
        BigDecimal temp = hct026Total.subtract(singleNow.add(singleCache).add(BigDecimal.valueOf(singleHistory)));
        if (temp.compareTo(BigDecimal.valueOf(0)) > 0) {
            temp = temp.multiply(BigDecimal.valueOf(0.5)).subtract(riskAmountCache).subtract(BigDecimal.valueOf(riskAmountHistory));
            illnessNow = illnessNow.add(temp);
            redisService.getCacheQuota(QuotaConstant.SORT_RISK_HCT026, insurantModel.getIdNo(), temp, requestModel.getPolicyInfo().getContNo());
        }
        BigDecimal illnessCache = redisService.getCacheQuota(QuotaConstant.SORT_A, insurantModel.getIdNo(), illnessNow, requestModel.getPolicyInfo().getContNo());

        // 累计重疾险保额（当前单+历史单）
        BigDecimal seriousIllnessTotal = illnessCache.add(illnessNow).add(BigDecimal.valueOf(illnessHistory));

        Date birthday = insurantModel.getBirthday();
        //获取日期相差的天数
        int days = DateUtil.getDays(birthday, valiDate);
        int years = DateUtil.getYears(birthday, valiDate);
        boolean flag = false;
        if (days >= UnderWriteConstant.AGE_THIRTY_DAY && years <= UnderWriteConstant.AGE_FORTY_YEAR) {
            if (AcceptUtil.compareTo(hct026Total, BigDecimal.valueOf(UnderWriteConstant.FIVE_HUNDRED_THOUSAND)) == 1) {
                return AcceptUtil.getInsuredResponse(UnderWriteConstant.UNDER_WRITE_FIAL_CODE,
                        String.format(UnderWriteConstant.UNDER_WRITE_NYGG0013_MESSAGE, insurantModel.getName()));
            }
            flag = seriousIllnessTotal.compareTo(BigDecimal.valueOf(UnderWriteConstant.FIVE_HUNDRED_THOUSAND)) == 1;
        } else if (years >= UnderWriteConstant.AGE_FORTY_ONE_YEAR && years <= UnderWriteConstant.AGE_FORTY_FIVE_YEAR) {
            if (AcceptUtil.compareTo(hct026Total, BigDecimal.valueOf(UnderWriteConstant.THREE_HUNDRED_THOUSAND)) == 1) {
                return AcceptUtil.getInsuredResponse(UnderWriteConstant.UNDER_WRITE_FIAL_CODE,
                        String.format(UnderWriteConstant.UNDER_WRITE_NYGG0014_MESSAGE, insurantModel.getName()));
            }
            flag = seriousIllnessTotal.compareTo(BigDecimal.valueOf(UnderWriteConstant.THREE_HUNDRED_THOUSAND)) == 1;
        } else if (years >= UnderWriteConstant.AGE_FORTY_SIX_YEAR && years <= UnderWriteConstant.AGE_FIFTY_YEAR) {
            if (AcceptUtil.compareTo(hct026Total, BigDecimal.valueOf(UnderWriteConstant.TWO_HUNDRED_THOUSAND)) == 1) {
                return AcceptUtil.getInsuredResponse(UnderWriteConstant.UNDER_WRITE_FIAL_CODE,
                        String.format(UnderWriteConstant.UNDER_WRITE_NYGG0015_MESSAGE, insurantModel.getName()));
            }
            flag = seriousIllnessTotal.compareTo(BigDecimal.valueOf(UnderWriteConstant.TWO_HUNDRED_THOUSAND)) == 1;
        } else if (years >= UnderWriteConstant.AGE_FIFTY_ONE_YEAR && years <= UnderWriteConstant.AGE_FIFTY_FIVE_YEAR) {
            if (AcceptUtil.compareTo(hct026Total, BigDecimal.valueOf(UnderWriteConstant.ONE_HUNDRED_THOUSAND)) == 1) {
                return AcceptUtil.getInsuredResponse(UnderWriteConstant.UNDER_WRITE_FIAL_CODE,
                        String.format(UnderWriteConstant.UNDER_WRITE_NYGG0016_MESSAGE, insurantModel.getName()));
            }
            flag = seriousIllnessTotal.compareTo(BigDecimal.valueOf(UnderWriteConstant.ONE_HUNDRED_THOUSAND)) == 1;
        }
        // 免体检额度校验
        if (flag) {
            return AcceptUtil.getInsuredResponse(UnderWriteConstant.UNDER_WRITE_FIAL_CODE, UnderWriteConstant.UNDER_WRITE_NYGG0012_MESSAGE);
        }
        return AcceptUtil.getInsuredResponse(AcceptConstant.RESULT_SUCCESS_CODE, AcceptConstant.RESULT_SUCCESS_MESSAGE);
    }


}
